require('buffer');
var https = require("https")
var express = require('express');
var router = express.Router();
var db = require("../util/DataBase.js")

var crypto = require('crypto');

var userService = require("../service/user.js");
var blackUserService = require("../service/black_user.js");

router.post('/set_user_state', function(req, res, next) {
  var body = req.body;

  var values = [
    body.state,
    req.session.user.id
  ];

  db.query("UPDATE user SET `state` = ? WHERE `id` = ?", values, function (err, results) {
    if(err) {
      res.json(null, -1, "设置用户状态失败");
      return;
    }

    req.session.user.state = values[0];

    res.json();

  });

});

router.post('/add_push_device_id', function(req, res, next) {
  if(req.session.hasOwnProperty("user") == false)
  {
    res.json(null);
    return;
  }

  var body = req.body;

  var values = [
    body.push_device_id,
    req.session.user.id
  ];

  userService.hasDeviceByPushDeviceId(values[0], values[1], (found) => {

    if(!found) {

      db.query("INSERT INTO `device` (`push_device_id`, `user_id`) VALUES (?, ?)", values, function(err, results) {

          if(err)
          {
              res.json(null, -1, "添加设备失败")
              return;
          }
          res.json(results.insertId);

      });

    } else {
      res.json(null);
    }

  }, () => {
    res.json(null, -1, "获取设备失败");
  });

});

router.get("/has_user", function (req, res, next) {

  var values = [
    req.query.phoneNumber
  ];

  db.query("SELECT `id` FROM `user` WHERE `phone_number` = ?", values, function(err, results) {

      if(err)
      {
          res.json(false, -1)
          return;
      }
      if(results.length > 0)
      {
          res.json(true);
      }
      else
      {
        res.json(false, 1)
      }

  });

});

router.post("/sms_vcode", function (req, res, next) {

  var body = req.body;

  var accountSID = "8a216da8679d0e9d0167c15a41e51578";

  var now = new Date();

  var ts = ( "0000" + now.getFullYear() ).substr(-4, 4) + ( "00" + (now.getMonth() + 1) ).substr(-2, 2) + ( "00" + now.getDate() ).substr(-2, 2) + ( "00" + now.getHours() ).substr(-2, 2) + ( "00" + now.getMinutes() ).substr(-2, 2) + ( "00" + now.getSeconds() ).substr(-2, 2);

  var vCode = "";
  for(var i =0; i < 6; ++ i ){
    vCode += parseInt(Math.random() * 10);
  }

  delete req.session.phoneNumberVerify;

  req.session.phoneNumberVerify = {
    phoneNumber: body.phoneNumber,
    vCode: vCode,
    ts: now.getTime()
  };

  var postData = JSON.stringify({
    "to": req.session.phoneNumberVerify.phoneNumber,
    "appId": "8a216da8679d0e9d0167c15a4233157e",
    "templateId": "431274",
    "datas": [
      req.session.phoneNumberVerify.vCode,
      "5分钟"
    ]
  });

  var md5 = crypto.createHash('md5');

  var options = {
    "hostname": "app.cloopen.com",
    "port": "8883",
    "path": "/2013-12-26/Accounts/" + accountSID + "/SMS/TemplateSMS?sig=" + md5.update(accountSID + "08be675e938f4ef489e2316ac4299140" + ts).digest('hex').toUpperCase(),
    "method": "POST",
    "headers": {
      "Accept": "application/json",
      "Content-Type": "application/json;charset=utf-8",
      "Authorization": Buffer.from(accountSID + ":" + ts).toString("base64"),
      'Content-Length': Buffer.byteLength(postData)
    }
  };

  const request = https.request(options);

  request.write(postData);

  request.end();

  res.json();

});

router.post("/reg", function (req, res, next) {

  var body = req.body;

  if(!( body.phoneNumber == req.session.phoneNumberVerify.phoneNumber && body.vCode == req.session.phoneNumberVerify.vCode ) || (( new Date().getTime() - req.session.phoneNumberVerify.ts ) > ( 1000 * 60 * 5 ))) {
    res.json(null, 2, "手机号码未通过验证");
    return;
  }

  var values = [
    body.phoneNumber,
    0,
    "http://aperturenx-banxian.oss-cn-beijing.aliyuncs.com/resource/default_avatar.jpg",
    "默认昵称",
    1
  ];

  db.query("INSERT INTO `user` (`phone_number`, `state`, `avatar_url`, `nickname`, `type`) VALUES (?, ?, ?, ?, ?)", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "创建用户失败")
      }
      else
      {
        res.json({
          id: results.insertId
        });
      }

  });

});

router.post('/login', function(req, res, next) {

  var body = req.body;

  if(!( body.phoneNumber == req.session.phoneNumberVerify.phoneNumber && body.vCode == req.session.phoneNumberVerify.vCode ) && !( ( body.phoneNumber + "" ) == "13401057020" && ( body.vCode + "" ) == "1234" ) || (( new Date().getTime() - req.session.phoneNumberVerify.ts ) > ( 1000 * 60 * 5 ))) {
    res.json(null, 2, "手机号码未通过验证");
    return;
  }

  var values = [
    body.phoneNumber
  ];

  db.query("SELECT `id`, `nickname`, `phone_number`, `avatar_url`, `state`, `type` FROM `user` WHERE `phone_number` = ?", values, function(err, results) {

      if(err)
      {
        res.json(null, -1, "系统错误")
        return;
      }
      if(results.length > 0)
      {
        req.session.user = results[0];
        res.json(results[0]);
      }
      else
      {
        res.json(null, 1)
      }

  });

});

router.post('/update_avatar', function (req, res, next) {
  var body = req.body;

  var values = [
    body.avatarUrl,
    req.session.user.id
  ];

  db.query("UPDATE user SET `avatar_url` = ? WHERE `id` = ?", values, function (err, results) {
    if(err) {
      res.json(null, -1, "设置头像失败");
      return;
    }

    req.session.user.avatar_url = body.avatarUrl;

    res.json(null);

  });

});

router.post('/update_nickname', function (req, res, next) {
  var body = req.body;

  var values = [
    body.nickName,
    req.session.user.id
  ];

  db.query("UPDATE user SET `nickname` = ? WHERE `id` = ?", values, function (err, results) {
    if(err) {
      res.json(null, -1, "设置昵称失败");
      return;
    }

    req.session.user.nickname = body.nickName;

    res.json(null);

  });

});

router.post('/logout', function (req, res, next) {
  delete req.session.user;
  res.json(null);
});

router.get('/islogin', function(req, res, next) {
  if(req.session.user)
  {
    db.query("SELECT `id`, `nickname`, `phone_number`, `avatar_url`, `state`, `type` FROM `user` WHERE `id` = ?", [req.session.user.id], function(err, results) {

        if(err)
        {
          res.json(null, -1, "系统错误")
          return;
        }
        if(results.length > 0)
        {
          res.json({
            login: true,
            user: results[0]
          })
        }
        else
        {
          res.json(null, 1)
        }

    });
  }
  else
  {
    res.json({
      login: false
    });

  }
});

router.get('/outsiders/:id', function(req, res, next) {

  var values = [
    req.params.id
  ];

  db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", values, function(err, results) {

      if(err)
      {
        res.json(null, -1, "系统错误")
        return;
      }
      if(results.length > 0)
      {
        db.query("SELECT topic.id as topic_id, `name`, `cover_url` FROM `follow_user_topic`, `topic` WHERE `user_id` = ? AND follow_user_topic.topic_id = topic.id", [
          req.params.id
        ], function (err, topicResults) {
            if(err) {
              res.json(null, -1, "获取主题失败");
            } else {
              results[0].follow_topic_list = topicResults;
              res.json(results[0]);
            }
        });
      }
      else
      {
        res.json(null, 1)
      }

  });

});

router.post('/cancel_block/:id', function (req, res, next) {

  blackUserService.isBlock(req.session.user.id, req.params.id * 1, (result) => {
    if(result) {

      var values = [
        req.session.user.id,
        req.params.id * 1
      ];

      db.query("DELETE FROM `block_user` WHERE `user_id` = ? AND `block_user_id` = ?", values, function (err, results) {
        if(err) {
          res.json();
          return;
        }

        res.json();

      });

    } else {

      res.json();

    }
  }, () => {
    res.json(null, -2, "获取屏蔽状态失败");
  });

});

router.post('/block/:id', function (req, res, next) {

  blackUserService.isBlock(req.session.user.id, req.params.id * 1, (result) => {
    if(result) {
      res.json();
    } else {

      var values = [
        req.session.user.id,
        req.params.id * 1
      ];

      db.query("INSERT INTO `block_user` (`user_id`, `block_user_id`) VALUES (?, ?)", values, function (err, results) {
        if(err) {
          res.json(null, -1, "屏蔽用户失败");
          return;
        }

        res.json();

      });

    }
  }, () => {
    res.json(null, -2, "获取屏蔽状态失败");
  });

});

router.post('/report/:id', function (req, res, next) {

  blackUserService.isReport(req.session.user.id, req.params.id * 1, (result) => {
    if(result) {
      res.json();
    } else {

      var values = [
        req.session.user.id,
        req.params.id * 1
      ];

      db.query("INSERT INTO `report_user` (`user_id`, `report_user_id`) VALUES (?, ?)", values, function (err, results) {
        if(err) {
          res.json(null, -1, "举报用户失败");
          return;
        }

        res.json();

      });

    }
  }, () => {
    res.json(null, -2, "获取举报状态失败");
  });

});

router.get('/is_block/:id', function (req, res, next) {

  var values = [
    req.session.user.id,
    req.params.id * 1
  ];

  blackUserService.isBlock(req.session.user.id, req.params.id * 1, (result) => {
    res.json(result);
  }, () => {
    res.json(false);
  });

});

router.get('/is_report/:id', function (req, res, next) {

  var values = [
    req.session.user.id,
    req.params.id * 1
  ];

  blackUserService.isReport(req.session.user.id, req.params.id * 1, (result) => {
    res.json(result);
  }, () => {
    res.json(false);
  });

});

module.exports = router;
